import axios from './axios'
import store from '../store'

const utils = {
  /**
   * 比较两个数组是否相等
   * @param {*} arr1
   * @param {*} arr2
   * @returns
   */

  compareArray(arr1, arr2) {
    if (arr1.length !== arr2.length) return false
    arr1 = arr1.sort()
    arr2 = arr2.sort()
    let len = arr1.length
    for (let i = 0; i < len; i++) {
      if (arr1[i] !== arr2[i]) return false
    }
    return true
  },
  /**
   * 判断浏览器类型
   */
  browserType() {
    const userAgent = navigator.userAgent // 取得浏览器的userAgent字符串
    const isOpera = userAgent.indexOf('Opera') > -1
    if (isOpera) {
      return 'Opera'
    }
    if (userAgent.indexOf('Firefox') > -1) {
      return 'Firefox'
    }
    if (userAgent.indexOf('Chrome') > -1) {
      return 'Chrome'
    }
    if (userAgent.indexOf('Safari') > -1) {
      return 'Safari'
    }
    if (userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && !isOpera) {
      return 'IE'
    }
  },

  /**
   * 是否有权限
   * @param {*} key
   * @returns
   */

  isAuth(key) {
    let list = key.split(',')
    let bool = true
    for (let i = 0; i < list.length; i++) {
      if (store.state.user.permList.indexOf(list[i]) === -1) {
        bool = false
        break
      }
    }
    return bool
  },
  /**
   * 清空登录信息
   */
  clearLoginInfo() {
    window.localStorage.removeItem('token')
    // 执行这个函数
    store.commit('resetStore')
  },

  /**
   * 获取前端字典
   * @param {类型} type
   * @returns
   */
  getDict(type) {
    if (type.indexOf('$') === 0) {
      let dict = store.state.common.dictListPrivate[type]
      if (typeof dict === 'object') {
        return dict || {}
      } else if (typeof dict === 'function') {
        return dict(utils.getDict)
      }
    }
  },

  /**
   * 发送浏览量
   * @param {*} to
   */
  sentRecord(to) {
    axios({
      url: axios.setUrl(`/article/record/${to.params.id}`),
      method: 'post',
      data: axios.setData({
        closeTm: '',
        openPage: to.path,
        openTm: new Date(),
        operatorBrowser: utils.browserType()
      })
    }).then(({ data }) => {
      if (data && data.code === 0) {
        // 成功后执行的操作
      } else {
        // 失败
      }
    })
  },

  /**
   * 日期格式化 1999-01-01 12:34:56
   * @param {*} date
   */
  formatDateTime(date) {
    var y = date.getFullYear()
    var m = date.getMonth() + 1
    m = m < 10 ? '0' + m : m
    var d = date.getDate()
    d = d < 10 ? '0' + d : d
    var h = date.getHours()
    h = h < 10 ? '0' + h : h
    var minute = date.getMinutes()
    minute = minute < 10 ? '0' + minute : minute
    var second = date.getSeconds()
    second = second < 10 ? '0' + second : second
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
  },
  /**
   * 日期格式化 1999-01-01
   * @param {*} date
   * @returns
   */
  formatDateTimeYMD(date) {
    const tem = new Date(date)
    var y = tem.getFullYear()
    var m = tem.getMonth() + 1
    m = m < 10 ? '0' + m : m
    var d = tem.getDate()
    d = d < 10 ? '0' + d : d

    return y + '-' + m + '-' + d
  },

  /**
   *
   * @param {*} date
   * @returns
   */
  getYearMonthDay(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()

    return {
      year,
      month,
      day
    }
  },

  /**
   * 获取图片src，图片是自己服务器的可以使用这个，比如头像
   * @param {*} fileKey
   * @param {*} domain
   * @returns
   */

  getImg(fileKey, domain = 'baseUrl') {
    return window.INIT_CONFIG[domain] + 'xxx' + '?fileKey' + fileKey + '&token=' + window.localStorage.getItem('token')
  },

  /**
   * 可以用这个方法自定义页面标题
   * @param {*} pageTitle
   * @returns
   */

  getDocumentTitle(pageTitle) {
    const defaultDocumentTitle = `个人空间`
    if (pageTitle) {
      return `${defaultDocumentTitle} - ${pageTitle}`
    }
    return `${defaultDocumentTitle}`
  },
  /**
   * 滚动到错误的dom位置
   * @param {*} dom
   * @param {*} selector
   */

  scrollToError(dom, selector = '.is-error') {
    let error = dom.querySelector(selector)
    if (error) {
      dom.offsetParent.scrollTop = error.offserTop
    }
  },

  /**
   * 代码高亮
   * @param {String} prop
   * @returns
   */

  heightLightTxt(filterTxt, text) {
    if (filterTxt === '') {
      return text
    }
    // 不区分大小写，这里用i
    const regexp = new RegExp(filterTxt, 'gi')

    return text.replace(regexp, `<span style="color:red">${filterTxt}</span>`)
  },

  /**
   * 下载文件
   * @param {*} url
   * @param {*} params
   * @param {*} domain
   */

  downloadCustomFile(url, params, domain = 'baseUrl') {
    const download_file = {}
    if (typeof download_file.iframe == 'undefined') {
      const iframe = document.createElement('iframe')
      download_file.iframe = iframe
      document.body.appendChild(download_file.iframe)
    }
    download_file.iframe.src = window.INIT_CONFIG[domain] + url + '?token' + window.localStorage.getItem('token')
  }
}

export default utils
